import { appConfig, base64Decode, getCookie, getUrlParam, login } from '@idmy/core'

interface RedirectUrl {
  redirect_uri?: string
}

interface UsernamePasswordParam extends RedirectUrl {
  client_id: string
  username: string
  password: string
  state?: string
  grant_type?: string
  device?: string
}

interface SmsCaptchaParam extends RedirectUrl {
  mobile: string
  state: string
}

interface AccessToken {
  access_token: string
  refresh_token: string
  id_token: string
  expires_in: number
  refresh_expires_in: number
  id: string
  scope: string
  state: string
}

function redirectUri(params: UsernamePasswordParam | SmsCaptchaParam) {
  params.redirect_uri = getUrlParam('redirectUri')
  if (!params.redirect_uri) {
    params.redirect_uri = location.origin + `/${appConfig.app.alias}`
  }
}

const parse = (tk: string) => {
  const arr = tk.split('.')
  const payload = base64Decode(arr.length == 4 ? arr[2] : arr[1])
  payload.iat || (payload.iat = Number(getCookie('iat')))
  return payload
}

async function afterLogin({ access_token, refresh_token, id_token }: AccessToken, redirectUri: string) {
  await login.setToken(access_token, refresh_token, id_token)
  location.replace(redirectUri)
  console.info(login.userInfo)
  console.info(login.accessInfo)
  console.info(login.refreshInfo)
}

async function login0(params: UsernamePasswordParam): Promise<void> {
  redirectUri(params)
  params.client_id = 'universe'
  params.grant_type = 'password'
  params.device = 'DEFAULT'
  const tmp = await http.postForm<AccessToken>('/oauth/token', params, { appKey: 'oauth' })
  return afterLogin(tmp, params.redirect_uri)
}

export const passwordLogin = async (params: UsernamePasswordParam): Promise<void> => {
  return login0(params)
}

export const sendSmsCaptcha = (mobile: string) =>
  http.post<string>(
    '/idm/sms',
    { mobile },
    {
      appKey: 'idm',
      encrypt: false,
    }
  )

export const getCaptcha = () => http.get('/idm/captcha', {}, { appKey: 'idm' })
